package student.aistar.layOrder.consumer;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;
import student.aistar.service.IOrderService;


import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;

import static student.aistar.config.RabbitMQConfig.*;

/**
 * 本类用来演示:  死信队列监听
 *
 * @author: qinFeng
 * @date: 2021/10/28 13:46
 */
//@Slf4j
@Component
public class DeadLetterQueueConsumer {
    @Autowired
    private IOrderService orderService;

    //监听死信队列A
    @RabbitListener(queues = DEAD_LETTER_QUEUE_A_NAME)
    @RabbitHandler
    public void receiveA(Message message, @Headers Map<String,Object> header, Channel channel){
        //获取消息
        String msg = new String(message.getBody());
        //记录日志
//        log.info("当前时间: {}, 死信队列A收到消息: {}, ", LocalDateTime.now(), msg);

        Long orderNumber = Long.valueOf(new String(message.getBody()));
        int orderStatus = orderService.selectOrdersStatus(orderNumber);
        if(orderStatus == 1)
            orderService.updateOrdersStatusDead(orderNumber);

        //手动删除rabbitmq队列中的数据的.
        long ack = (long) header.get(AmqpHeaders.DELIVERY_TAG);
        try {
            channel.basicAck(ack,false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //监听死信队列B
    @RabbitListener(queues = DEAD_LETTER_QUEUE_B_NAME)
    @RabbitHandler
    public void receiveB(Message message, Channel channel){
        //获取消息
        String msg = new String(message.getBody());

        //记录日志
//        log.info("当前时间: {}, 死信队列B收到消息: {}, ", LocalDateTime.now(), msg);
    }
}
